package com.skt.config;

import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.Duration;
import java.util.concurrent.TimeUnit;

@Slf4j
@Configuration
public class RedissonConfig {

    @Value("${spring.redis.host:localhost}")
    private String redisHost;

    @Value("${spring.redis.port:6379}")
    private String redisPort;

    @Value("${spring.redis.password:}")
    private String redisPassword;

    @Value("${spring.redis.database:1}")
    private int redisDatabase;

    @Value("${spring.redis.timeout:3000ms}")
    private String redisTimeout;

    @Bean(destroyMethod = "shutdown")
    public RedissonClient redissonClient() {
        try {
            log.info("🔧 开始配置Redisson客户端...");
            log.info("Redis连接参数: host={}, port={}, database={}, timeout={}",
                    redisHost, redisPort, redisDatabase, redisTimeout);

            Config config = new Config();

            // 解析超时时间
            long timeoutMs = parseTimeoutToMillis(redisTimeout);
            int timeoutSeconds = (int) (timeoutMs / 1000);

            // 单节点配置
            config.useSingleServer()
                    .setAddress("redis://" + redisHost + ":" + redisPort)
                    .setPassword(redisPassword.isEmpty() ? null : redisPassword)
                    .setDatabase(redisDatabase)
                    .setConnectTimeout(timeoutSeconds * 1000) // 连接超时（毫秒）
                    .setTimeout(timeoutSeconds * 1000)         // 命令超时（毫秒）
                    .setRetryAttempts(3)                      // 重试次数
                    .setRetryInterval(1500)                   // 重试间隔（毫秒）
                    .setConnectionPoolSize(10)                // 连接池大小
                    .setConnectionMinimumIdleSize(5);         // 最小空闲连接

            log.info("✅ Redisson配置创建完成，开始连接Redis...");

            RedissonClient redissonClient = Redisson.create(config);

            // 测试连接是否成功
            boolean isConnected = testRedissonConnection(redissonClient);
            if (isConnected) {
                log.info("✅ Redisson客户端连接成功: {}:{}", redisHost, redisPort);
                return redissonClient;
            } else {
                log.error("❌ Redisson连接测试失败");
                throw new RuntimeException("Redisson连接测试失败");
            }

        } catch (Exception e) {
            log.error("❌ Redisson客户端初始化失败", e);
            throw new RuntimeException("Redisson初始化失败: " + e.getMessage(), e);
        }
    }

    /**
     * 测试Redisson连接
     */
    private boolean testRedissonConnection(RedissonClient redissonClient) {
        try {
            // 简单的ping测试
            boolean pingResult = redissonClient.getNodesGroup().pingAll();
            if (pingResult) {
                log.info("✅ Redisson连接测试成功");
                return true;
            } else {
                log.warn("⚠️ Redisson连接测试返回false");
                return false;
            }
        } catch (Exception e) {
            log.error("❌ Redisson连接测试异常: {}", e.getMessage());
            return false;
        }
    }

    /**
     * 解析超时时间字符串为毫秒
     */
    private long parseTimeoutToMillis(String timeoutStr) {
        if (timeoutStr == null || timeoutStr.isEmpty()) {
            return 3000L;
        }

        try {
            timeoutStr = timeoutStr.toLowerCase().trim();
            if (timeoutStr.endsWith("ms")) {
                return Long.parseLong(timeoutStr.replace("ms", ""));
            } else if (timeoutStr.endsWith("s")) {
                return Long.parseLong(timeoutStr.replace("s", "")) * 1000;
            } else {
                return Long.parseLong(timeoutStr);
            }
        } catch (NumberFormatException e) {
            log.warn("无法解析超时时间: {}, 使用默认值3000ms", timeoutStr);
            return 3000L;
        }
    }
}